package org.xiaoyu.rpc.remoting.transport.server;

import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.common.constant.RpcStatusCode;
import org.xiaoyu.rpc.common.extension.ExtensionLoader;
import org.xiaoyu.rpc.remoting.RequestHandler;
import org.xiaoyu.rpc.remoting.packet.*;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created By Have
 * 2021/7/5 14:16
 */
@ChannelHandler.Sharable
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<Packet> {
    public static final NettyServerHandler INSTANCE = new NettyServerHandler();
    private static final RequestHandler requestHandler = ExtensionLoader.getExtensionLoader(RequestHandler.class).getExtension("rpc");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Packet msg) throws Exception {
        if (msg instanceof Invocation) {
            Invocation invocation = (Invocation) msg;
            Result result = requestHandler.handle(ctx.channel(), invocation);
            ctx.executor().execute(new Runnable() {
                @Override
                public void run() {
                    ctx.writeAndFlush(new AppResponse(PacketStatusConstant.SUCCESS, result, invocation.getRequestId()));
                }
            });
        } else if (msg instanceof HeartbeatRequest) {

        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("连接发生错误:[{}]", cause.getMessage());
        cause.printStackTrace();
        ctx.channel().close();
    }
}
